/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年6月26日
 * @version 0.1
 */
package com.suredy.base.ctrl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.suredy.base.model.Menu;
import com.suredy.base.model.MenuTreeModel;
import com.suredy.base.model.Resource;
import com.suredy.base.model.ResourceType;
import com.suredy.base.service.MenuSrv;
import com.suredy.base.service.ResourceSrv;
import com.suredy.base.service.UserSrv;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.tools.SuredyMessageModel;
import com.suredy.tools.SuredyTreeModel;

/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value = "config")
public class NavigationCtrl extends BaseCtrl {

	private final static Logger log = LoggerFactory.getLogger(NavigationCtrl.class);
	
	@Autowired
	private MenuSrv menuSrv;

	@Autowired 
	ResourceSrv resourceSrv;
	
	@Autowired
	private UserSrv userSrv;
	
	@RequestMapping({"menu-user"})
	@ResponseBody
	public Object UserMenuTree() {
		String userCode = (String) SecurityUtils.getSubject().getPrincipal();
		// 已授权用户访问的安全资源点
		Set<String> userSecurityResources = this.userSrv.getPermissions(userCode);
		// 全部菜单相关的安全资源点
		List<Resource> menues = this.resourceSrv.getAll(ResourceType.Menu);
		// 已授权用户访问的菜单相关安全资源点
		List<String> allowedMenues = new ArrayList<String>();
		for (Resource menu : menues) {
			if (userSecurityResources.contains(menu.getId())) {
				allowedMenues.add(menu.getId());
			}
		}
		
		List<MenuTreeModel> tree = this.menuSrv.getUserMenuTree(null, allowedMenues);

		MenuTreeModel root = new MenuTreeModel();
		root.setText("Root");
		root.setCollapse(false);
		

		if (tree != null) {
			root.setLeaf(false);
			root.setChildren(new ArrayList<SuredyTreeModel>());
			root.getChildren().addAll(tree);
		} else {
			root.setLeaf(true);
		}

		return root;
	}
	
//	@RequestMapping(value = "menu-user")
//	public ModelAndView MenuUser() {
//		ModelAndView view = new ModelAndView("config/menu-user");
//		return view;
//	}
	
	
	@RequestMapping("menu-tree")
	@ResponseBody
	public Object ManagerMenuTree() {
		List<MenuTreeModel> tree = this.menuSrv.getMenuTree(null);

		MenuTreeModel root = new MenuTreeModel();
		root.setText("Root");
		root.setCollapse(false);
		

		if (tree != null) {
			root.setLeaf(false);
			root.setChildren(new ArrayList<SuredyTreeModel>());
			root.getChildren().addAll(tree);
		} else {
			root.setLeaf(true);
		}

		return root;
	}
	
	@RequestMapping(value = "menu-manager")
	public ModelAndView MenuManager() {
		ModelAndView view = new ModelAndView("config/menu-manager");
		return view;
	}
	
	@RequestMapping(value = "menu-create")
	public ModelAndView MenuCreate() {
		ModelAndView view = new ModelAndView("config/menu-create");
		List<Resource> resources = this.resourceSrv.getAll(ResourceType.Menu);
		view.addObject("resources", resources);
		return view;
	}
	
	
	@RequestMapping("menu-create-save")
	@ResponseBody
	public Object MenuCreate(HttpServletRequest request) {
		String parentId = request.getParameter("parentId");
		String text = request.getParameter("text");
		String url = request.getParameter("url");
		String sort = request.getParameter("sort");
		String icon = request.getParameter("icon");
		String active = request.getParameter("active");
		String collapse = request.getParameter("collapse");
		String resourceId = request.getParameter("resourceId");
		
		if (StringUtils.isBlank(url) || StringUtils.isBlank(text)) {
			return SuredyMessageModel.createErrorMessage("参数不足, URL和名称必须填写", null);
		}

		Menu menu = new Menu();
		menu.setUrl(url);
		menu.setText(text);
		menu.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		menu.setIcon(StringUtils.isBlank(icon) ? null : icon);
		menu.setActive(Boolean.valueOf(active));
		menu.setCollapse(Boolean.valueOf(collapse));
		menu.setResourceId(StringUtils.isBlank(resourceId) ? null : resourceId);

		if (!StringUtils.isBlank(parentId)) {
			menu.setParent(new Menu());
			menu.getParent().setId(parentId);
		}

		this.menuSrv.save(menu);

		return SuredyMessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "menu-edit")
	public ModelAndView MenuEdit(String menuId) {
		ModelAndView view = new ModelAndView("config/menu-edit");
		if (StringUtils.isBlank(menuId)) {
			log.info("Parameter String[menuId] is blank.");
			return view;
		}
		Menu menu = this.menuSrv.get(menuId);
		Menu parent = menu.getParent();
		if (parent == null) {
			parent = new Menu();
			parent.setText("Root");
			parent.setId("");
		}
		List<Resource> resources = this.resourceSrv.getAll(ResourceType.Menu);
		view.addObject("resources", resources);
		view.addObject("menu", menu);
		view.addObject("parent", parent);
		return view;
	}
	
	@RequestMapping("menu-edit-save")
	@ResponseBody
	public Object MenuEdit(HttpServletRequest request) {
		String id = request.getParameter("id");
		String parentId = request.getParameter("parentId");
		String text = request.getParameter("text");
		String url = request.getParameter("url");
		String sort = request.getParameter("sort");
		String icon = request.getParameter("icon");
		String active = request.getParameter("active");
		String collapse = request.getParameter("collapse");
		String resourceId = request.getParameter("resourceId");
		
		if (StringUtils.isBlank(id)) {
			return SuredyMessageModel.createErrorMessage("参数错误, 菜单ID不能为空", null);
		}
		
		Menu menu = this.menuSrv.get(id);
		if (menu == null) {
			return SuredyMessageModel.createErrorMessage("参数错误, 未找到与ID对应的菜单信息", null);
		}
		if (StringUtils.isBlank(url) || StringUtils.isBlank(text)) {
			return SuredyMessageModel.createErrorMessage("参数不足, URL和名称必须填写", null);
		}
		
		menu.setUrl(url);
		menu.setText(text);
		menu.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		menu.setIcon(StringUtils.isBlank(icon) ? null : icon);
		menu.setActive(Boolean.valueOf(active));
		menu.setCollapse(Boolean.valueOf(collapse));
		menu.setResourceId(StringUtils.isBlank(resourceId) ? null : resourceId);
		

		if (!StringUtils.isBlank(parentId)) {
			if (parentId.equals(id)) {
				// set self as parent then set parent as null.
				menu.setParent(null);
			} else {
				menu.setParent(new Menu());
				menu.getParent().setId(parentId);
			}
		} else {
			menu.setParent(null);
		}

		this.menuSrv.update(menu);

		return SuredyMessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping("menu-delete")
	@ResponseBody
	public Object MenuDelete(String menuId) {
		if (StringUtils.isBlank(menuId)) {
			return SuredyMessageModel.createErrorMessage("无效的菜单ID！", null);
		}

		Menu menu = this.menuSrv.get(menuId);

		if (menu == null) {
			return SuredyMessageModel.createErrorMessage("未找到与ID对应的菜单信息！", null);
		}

		try {
			this.menuSrv.delete(menu);
		} catch (Exception e) {
			return SuredyMessageModel.createErrorMessage("删除不成功,菜单信息映射错误！", null);
		}

		return SuredyMessageModel.createSuccessMessage(null, null);
	}
}
